package Long.Lu.realm;


import Long.Lu.Service.UserInfoService;
import Long.Lu.pojo.UserInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    //注入sevice
    @Autowired
    UserInfoService userInfoService;
    /*注入Dao*/


    /**
     * 授权
     * //@param principals
     * //@return
     */
   @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1 拿到认证通过的用户名
       String userName = principals.fromRealm(this.getName()).iterator().next()+"";
       // 2 查询用户拥有的权限或者角色

        // 创建权限
        List<String> lisPower = new ArrayList<>();
        List<String> lisRole = new ArrayList<>();
        if(userName.equals("rock")){
            lisPower.add("A");
            lisPower.add("B");
            lisPower.add("C");
            lisPower.add("D");
            lisPower.add("E");

        }else if(userName.equals("tt")) {
            lisPower.add("A");
        }if(userName.equals("rr")){
            lisPower.add("E");
        }else if (userName.equals("yy")){
            lisPower.add("B");
        }

        //3 吧权限和角色添加到shiro的授权对象里
        SimpleAuthorizationInfo au = new SimpleAuthorizationInfo();
        au.addStringPermissions(lisPower);
        ;au.addRoles(lisRole);
        return au;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1 拿到用户名
        UsernamePasswordToken upt = (UsernamePasswordToken)token;
        String userName = upt.getPrincipal()+"";
        //2 从数据库中取出用户名的加密的密码
        UserInfo userInfo = userInfoService.selectByName(userName);
        //3 创建 密码校验的凭证对象
        AuthenticationInfo  auto = new SimpleAuthenticationInfo(
                userInfo.getUserName(),userInfo.getUserPwd(),new Md5Hash(userName),this.getName());
        return auto;
    }

}
